/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/IServerModule.hpp"
#include "Xern/ISoundEngine.hpp"
#include "Xern/IMetaverseClient.hpp"
#include "Xern/IMetaverseNodeFactory.hpp"
#include "Xern/PluginRegistrator.hpp"
#include "Xern/Engine.hpp"
#include "Xern/Exceptions.hpp"
#include "Xern/Log.hpp"
#include "Xern/Region.hpp"
#include "ClientModule.hpp"

namespace XernClient
{
	static PluginRegistrator<ClientModule>
	clientModule("Client", "XernClient");

	ClientModule::ClientModule()
	{
		inputController.reset(new InputController());
		isConnected = false;
	}

	ClientModule::~ClientModule()
	{
	}

	void ClientModule::Initialize()
	{
		Engine &engine = Engine::Get();

		// Create the client console.
		console.reset(new Console());

		// Register it with the master console.
		boost::shared_ptr<Console> masterConsole =
			boost::dynamic_pointer_cast<Console> (engine.GetMasterConsole());
		masterConsole->RegisterSubConsole(console);

		// Register the console commands.
		console->RegisterCommand(ConsoleCommand(&ClientModule::LoginCommand, this,
						"login", "Log-ins into a metaverse"));
		console->RegisterCommand(ConsoleCommand(&ClientModule::LogoutCommand, this,
								"logout", "Log-out from the metaverse"));
		console->RegisterCommand(ConsoleCommand(&ClientModule::SayCommand, this,
								"say", "Sends a chat message"));

		// Initialize the input controller.
		inputController->Initialize();

		// Run the client script.
		try
		{
			engine.GetScriptEngine()->RunScript("media/scripts/client/client.nut");
		}
		catch(XernException &e)
		{
			LogConsole->Error("Failed to run the client script: %s.", e.what());
		}
	}

	void ClientModule::Shutdown()
	{
		Engine &engine = Engine::Get();

		// Shutdown the input controller.
		inputController->Shutdown();

		// Log-out and shutdown.
		if(metaverseClient)
		{
			metaverseClient->Logout();
			metaverseClient->Shutdown();
		}


		// Unregister the client console.
		boost::shared_ptr<Console> masterConsole =
				boost::dynamic_pointer_cast<Console> (engine.GetMasterConsole());
		//masterConsole->UnregisterSubConsole(console);

		// Destroy the client console.
		console.reset();
	}

	void ClientModule::BeginRegionLoad()
	{
		// Set the current camera.
		boost::shared_ptr<IRenderer> renderer = Engine::Get().GetRenderer();
		renderer->SetCurrentCamera(boost::shared_ptr<ICamera> ());

		// Release the player entity.
		playerEntity.reset();
		camera.reset();
		inputController->SetPlayerEntity(playerEntity);
	}

	void ClientModule::RegionLoaded(boost::shared_ptr<Region> region)
	{
		if(!region)
			return;

		// Check for remote server.
		if(isConnected)
		{
			// Create the player constroller.
			playerEntity = metaverseClient->CreatePlayerController(region);
		}
		else
		{
			// Get the server module.
			boost::shared_ptr<IServerModule> server = Engine::Get().GetServerModule();
			if(!server)
				return;

			// Create the player entity.
			playerEntity = server->CreatePlayerController(region);
		}

		// Check the player controller.
		if(!playerEntity)
		{
			LogConsole->Notify("Failed to create the player controller.");
			return;
		}

		// Create the player camera.
		boost::shared_ptr<IRenderer> renderer = Engine::Get().GetRenderer();
		camera = renderer->CreateCamera("Player1Camera");
		playerEntity->AddResource(camera);

		// Move the camera into the eyes.
		const float EyesSinceCenter = 0.72f;
		OrthoTransform trans;
		trans.SetVector(Vector3(0.0f, EyesSinceCenter, 0.0f));
		camera->SetTransform(trans);

		// Set the current camera.
		renderer->SetCurrentCamera(camera);

		// Create the sound listener.
		boost::shared_ptr<ISoundEngine> soundEngine =
				Engine::Get().GetSoundEngine();
		listener = soundEngine->CreateListener();
		listener->SetTransform(trans);
		playerEntity->AddResource(listener);

		// Set the current listener.
		soundEngine->SetCurrentListener(listener);

		// Activate the input controller.
		inputController->SetPlayerEntity(playerEntity);
		inputController->Activate();

		LogConsole->Notify("Created player controller.");
	}

	bool ClientModule::Frame(float delta)
	{
		// Process input.
		inputController->Think(delta);

		// Process the sound.
		boost::shared_ptr<ISoundEngine> sound = Engine::Get().GetSoundEngine();
		sound->Frame(delta);

		// Process the network.
		if(isConnected)
			metaverseClient->Frame(delta);

		return true;
	}

	void ClientModule::AngleChange(const Quaternion &angle)
	{
		if(!camera)
			return;

		// Change the transform matrix.
		OrthoTransform trans = camera->GetTransform();
		trans.SetMatrix(QRotMatrix3(angle));
		camera->SetTransform(trans);
		listener->SetTransform(trans);
	}

	int ClientModule::LoginCommand(int argc, const char *argv[])
	{
		const char *HelpString =
				"login [options] <host>\n"
				"-u [user/first name]\n"
				"-l [last name]\n"
				"-p [password]\n"
				"-m [protocol]";

		std::string host;
		std::string username;
		std::string lastname;
		std::string password;
		std::string protocol = "Xern";

		for(int i = 1; i <argc; i++)
		{
			if(!strcmp(argv[i], "-u"))
			{
				username = argv[++i];
			}
			else if(!strcmp(argv[i], "-l"))
			{
				lastname = argv[++i];
			}
			else if(!strcmp(argv[i], "-p"))
			{
				password = argv[++i];
			}
			else if(!strcmp(argv[i], "-m"))
			{
				protocol = argv[++i];
			}
			else if(!strcmp(argv[i], "-h") ||
					!strcmp(argv[i], "-help") ||
					!argv[i][0] == '-')
			{
				LogConsole->Usage(HelpString);
				return -1;
			}
			else
			{
				host = argv[i];
			}
		}

		if(host.empty())
		{
			LogConsole->Usage(HelpString);
			return -1;
		}

		// Shutdown the old client.
		if(metaverseClient)
			metaverseClient->Shutdown();

		// Find the protocol.
		boost::shared_ptr<IMetaverseNodeFactory> nodeFactory
		= Engine::Get().GetPluginRegistry()
			->QueryInterface<IMetaverseNodeFactory> ("MetaverseProtocol", protocol);
		if(!nodeFactory)
		{
			LogConsole->Error("Failed to query '%s' protocol plugin.", protocol.c_str());
			return -1;
		}

		// Create a metaverse client if needed.
		metaverseClient = nodeFactory->CreateClient();

		// Initialize the client.
		metaverseClient->Initialize();

		// Perform login.
		metaverseClient->SetLoginServer(host);
		isConnected = true;
		if(!metaverseClient->Login(username, lastname, password))
			isConnected = false;

		return 0;
	}

	int ClientModule::LogoutCommand(int argc, const char *argv[])
	{
		if(metaverseClient)
			metaverseClient->Logout();

		isConnected = false;
		return 0;
	};

	int ClientModule::SayCommand(int argc, const char *argv[])
	{
		if(argc < 1)
		{
			LogConsole->Usage("say [message]");
			return -1;
		}

		// Send to the metaverse.
		if(metaverseClient)
			metaverseClient->ChatMessage(argv[1]);

		return 0;
	}
}; // namespace XernClient
